<!-- 对 divider 组件的编辑 -->
<template>
  <div class="articles-edit" v-if="dialogShow">
    <SetDesignDialog :title="name" :dialogVisible="dialogShow" :close="close" :saveclose="saveclose"
      ref="settingComponentDialog">
      <div class="edit-container-u">
        <el-tabs v-model="activeName">
          <el-tab-pane label="设置" name="1">
            <el-row>
              <el-col :span="12">
                <el-form :label-width="'140px'">
                  <el-form-item label="是否显示分类" style="margin-bottom:0px;">
                    <el-select :disabled="disableShowSort" style="width:120px;" size="mini"
                      v-model="data.config.showSort" placeholder="请选择">
                      <el-option label="显示" :value="1"></el-option>
                      <el-option label="不显示" :value="0"></el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
              </el-col>
              <el-col :span="12">
                <el-form :label-width="'140px'">
                  <el-form-item label="是否显示时间" style="margin-bottom:0px;">
                    <el-select :disabled="disableShowTime" style="width:120px;" size="mini"
                      v-model="data.config.showTime" placeholder="请选择">
                      <el-option label="显示" :value="1"></el-option>
                      <el-option label="不显示" :value="0"></el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form :label-width="'140px'">
                  <el-form-item label="分类链接打开方式" style="margin-bottom:0px;">
                    <el-select :disabled="disableShowSort" style="width:160px;" size="mini"
                      v-model="data.config.ctarget" placeholder="请选择">
                      <el-option label="当前页面跳转" :value="'_self'"></el-option>
                      <el-option label="新打开页面跳转" :value="'_blank'"></el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
              </el-col>
              <el-col :span="12">
                <el-form :label-width="'140px'">
                  <el-form-item label="文章链接打开方式" style="margin-bottom:0px;">
                    <el-select style="width:160px;" size="mini" v-model="data.config.atarget" placeholder="请选择">
                      <el-option label="当前页面跳转" :value="'_self'"></el-option>
                      <el-option label="新打开页面跳转" :value="'_blank'"></el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form :label-width="'140px'">
                  <el-form-item label="图片显示比例" style="margin-bottom:0px;">
                    <el-select :disabled="disableRatio" style="width:120px;" size="mini" v-model="data.config.ratio"
                      placeholder="请选择">
                      <el-option label="1:1" :value="'1:1'"></el-option>
                      <el-option label="4:3" :value="'4:3'"></el-option>
                      <el-option label="3:4" :value="'3:4'"></el-option>
                      <el-option label="3:2" :value="'3:2'"></el-option>
                      <el-option label="2:3" :value="'2:3'"></el-option>
                      <el-option label="16:9" :value="'16:9'"></el-option>
                      <el-option label="9:16" :value="'9:16'"></el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
              </el-col>
              <el-col :span="12">
                <FontWeight :formLabelWidth="'140px'" :defValue="data.config.title.fontWeight"
                  :chgValue="(d)=>{data.config.title.fontWeight = d}" />
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form :label-width="'140px'">
                  <el-form-item label="单行 / 滚动显示条数" style="margin-bottom:0px;">
                    <el-select :disabled="disableVis" style="width:120px;" size="mini" v-model="data.config.vis"
                      placeholder="请选择">
                      <el-option label="2" :value="2"></el-option>
                      <el-option label="3" :value="3"></el-option>
                      <el-option label="4" :value="4"></el-option>
                      <el-option label="5" :value="5"></el-option>
                      <el-option label="6" :value="6"></el-option>
                      <el-option label="7" :value="7"></el-option>
                      <el-option label="8" :value="8"></el-option>
                      <el-option label="9" :value="9"></el-option>
                      <el-option label="10" :value="10"></el-option>
                      <el-option label="11" :value="11"></el-option>
                      <el-option label="12" :value="12"></el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
              </el-col>
              <el-col :span="12">
                <el-form :label-width="'140px'" @submit.native.prevent>
                  <el-form-item label="更多链接内容" style="margin-bottom:0px;">
                    <el-input :disabled="disableViewDetaits" size="mini" style="width:120px;"
                      v-model="data.config.viewDetaits" maxlength="12">
                    </el-input>
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form :label-width="'140px'">
                  <el-form-item label="懒加载" style="margin-bottom:0px;">
                    <el-select size="mini" style="width:120px;" v-model="data.config.islazyload" placeholder="请选择">
                      <el-option label="关闭" :value="0"></el-option>
                      <el-option label="开启" :value="1"></el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="数据选取" name="2">
            <ChooseArticlesSystemData :changeQuoteSystemInput="d=>{quoteSystemInput =  d.join(' ')}"
              ref="chooseArticlesSystemData" :quoteSystem="quoteSystem" />
          </el-tab-pane>
          <el-tab-pane label="列表样式" name="3">
            <el-form :label-width="'80px'" @submit.native.prevent>
              <el-form-item label="当前样式" style="margin-bottom:0px;">
                <el-input size="mini" style="width:260px;" :disabled="true" v-model="styleTypeInput" maxlength="12">
                </el-input>
              </el-form-item>
            </el-form>
            <div class="iframe" v-loading="iframeLoading">
              <iframe :src="iframeSrc" frameborder="0" style="width:100%;height:400px;" ref="iframeRender"></iframe>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </SetDesignDialog>
  </div>
</template>

<script>
import adnewsImage from '@/assets/images/adnewsStyle.png'
import SetDesignDialog from '@/components/common/dialog/SetDesignDialog.vue'
import ChooseArticlesSystemData from '@/components/common/design/dialog/component/articles/ChooseArticlesSystemData.vue'
import TextAlign from '@/components/common/design/dialog/component/formitem/TextAlign.vue'
import TablesSystemType1 from '@/components/common/design/dialog/component/articles/TablesSystemType1.vue'
import TablesSystemType2 from '@/components/common/design/dialog/component/articles/TablesSystemType2.vue'
import TablesSystemType3 from '@/components/common/design/dialog/component/articles/TablesSystemType3.vue'
import TablesSystemType4 from '@/components/common/design/dialog/component/articles/TablesSystemType4.vue'
import FontWeight from '@/components/common/design/dialog/component/formitem/FontWeight.vue'
import * as WindowType from '@/config/windowtype.js'
// import * as PubsubType from '@/config/pubsubtype.js'
import * as functions from '@/core/functions.js'
import VueFunctions from '@/core/VueFunctions.js'
import BackendjsFunctions from '@/core/BackendjsFunctions.js'
import { mapState } from 'vuex'
// import PubSub from 'pubsub-js'
import crypto from '@/core/crypto.js'
import qs from 'qs'
import _ from 'lodash'

export default {
  computed: {
    ...mapState([
      'design'
    ]),
    styleTypeInput () {
      return '编号: ' + this.data.theme
    },
    chooseItemsContent () {
      return '共选择了' + this.quoteSystem.quoteSystemItemIds.length + '个, 还可以选择' + (36 - this.quoteSystem.quoteSystemItemIds.length) + '个'
    },
    // 是否可以编辑分类是否显示
    disableShowSort () {
      if (this.systemTypeId === 2) {
        return true
      }
      let currentConf = this.getCurrentConf()
      let bool = !currentConf.showSort
      return bool
    },
    // 是否可以编辑时间是否显示
    disableShowTime () {
      let currentConf = this.getCurrentConf()
      let bool = !currentConf.showTime
      return bool
    },
    // 是否可以编辑图片的显示比例
    disableRatio () {
      if (this.systemTypeId === 2) {
        return true
      }
      let currentConf = this.getCurrentConf()
      let bool = !currentConf.ratio
      if (bool) {
        return bool
      }
    },
    // 是否可以编辑图片的滚动显示条数
    disableVis () {
      if (this.systemTypeId === 2) {
        return true
      }
      let currentConf = this.getCurrentConf()
      let bool = !currentConf.vis
      if (bool) {
        return bool
      }
    },
    // 是否可以编辑更多链接内容
    disableViewDetaits () {
      let currentConf = this.getCurrentConf()
      let bool = !currentConf.viewDetaits
      if (bool) {
        return bool
      }
    }
  },
  created () {
    VueFunctions.method(WindowType.EDIT_COMPONENT_WITH_COMPONENTARTICLES, (bjComponent) => {
      this.close()
      this.dialogShow = true
      this.bjComponent = bjComponent
      this.data = bjComponent.render.data
      // ....
      this.quoteSystem = bjComponent._other.quoteSystem
      if (!this.quoteSystem || !this.quoteSystem.type) {
        this.quoteSystem = {
          // componentId: '',
          // hostId: this.$store.state.host.id,
          // siteId: this.$store.state.site.id,
          // createAt: [],
          // id: 66,
          type: 1,
          quotePageId: 0,
          quoteSystemId: 0,
          quoteSystemCategoryId: 0,
          topCount: 4,
          quoteSystemItemIds: '', // []需转换成字符串传递
          remark: '' // {} 需转换成字符串传递
        }
      }

      this.iframeStyle = {
        width: 825,
        row: 6,
        col: 4,
        compname: 'component_articles',
        theme: this.$store.state.site.config.theme,
        color: this.$store.state.site.config.color,
        ttextalign: 'center',
        tcolor: '#888',
        now: new Date().getTime()
      }
      this.iframeStyle.token = crypto.en(JSON.stringify(this.iframeStyle))
      let query = qs.stringify(this.iframeStyle)

      // iframe
      this.iframeSrc = '/api/udin/articles?' + query

      this.$nextTick(() => {
        this.$refs['settingComponentDialog'].open()
        if (this.$refs['chooseArticlesSystemData']) {
          this.$refs['chooseArticlesSystemData'].open()
        }
      })

      // iframe 加载完成后回调的方法，
      let funcname = WindowType.API_UDIN_COMPONENT_ONLOAD_.replace('[ComponentName]', this.iframeStyle.compname).toUpperCase()
      window[funcname] = () => {
        this.iframeLoading = false
        let renderObj = {
          imgSrc: adnewsImage,
          css: [
            { 'width': '175px', 'height': '135px', 'background-position': '-2px 0' },
            { 'width': '175px', 'height': '135px', 'background-position': '-200px 0' },
            { 'width': '175px', 'height': '135px', 'background-position': '-398px 0' },
            { 'width': '175px', 'height': '135px', 'background-position': '-596px 0' },
            { 'width': '175px', 'height': '135px', 'background-position': '-2px -156px' },
            { 'width': '175px', 'height': '135px', 'background-position': '-200px -156px' },
            { 'width': '175px', 'height': '135px', 'background-position': '-398px -156px' },
            { 'width': '175px', 'height': '135px', 'background-position': '-596px -156px' },
            { 'width': '175px', 'height': '135px', 'background-position': '-2px -295px' },
            { 'width': '175px', 'height': '135px', 'background-position': '-200px -295px' },
            { 'width': '175px', 'height': '135px', 'background-position': '-398px -295px' },
            { 'width': '175px', 'height': '135px', 'background-position': '-596px -295px' },
            { 'width': '175px', 'height': '135px', 'background-position': '-200px -423px' },
            { 'width': '175px', 'height': '135px', 'background-position': '-2px -423px' },
            { 'width': '175px', 'height': '135px', 'background-position': '-398px -423px' },
            { 'width': '175px', 'height': '135px', 'background-position': '-596px -423px' },
            { 'width': '175px', 'height': '135px', 'background-position': '-2px -560px' },
            { 'width': '175px', 'height': '135px', 'background-position': '-200px -560px' },
            { 'width': '175px', 'height': '135px', 'background-position': '-398px -560px' },
            { 'width': '175px', 'height': '135px', 'background-position': '-596px -560px' },
            { 'width': '175px', 'height': '135px', 'background-position': '-2px -698px' },
            { 'width': '175px', 'height': '135px', 'background-position': '-200px -698px' },
            { 'width': '175px', 'height': '135px', 'background-position': '-398px -698px' },
            { 'width': '175px', 'height': '135px', 'background-position': '-596px -698px' }
          ]
        }
        // 调用 iframe 中的 render 方法进行渲染
        this.$refs['iframeRender'].contentWindow.render(renderObj, this.data.theme)
      }

      // 选择theme后回调的方法，并且传入选择的数据
      let funcallbackname = WindowType.API_UDIN_COMPONENT_ONLOAD_CALLBACK_.replace('[ComponentName]', this.iframeStyle.compname).toUpperCase()
      window[funcallbackname] = (theme) => {
        this.data.theme = '' + theme
      }
    })
  },
  mounted () {
    // PubSub.subscribe(PubsubType.PUBSUB_DIGLOG_COMPONENT_CLOSE, (event, data) => {
    //   this.close()
    // })
    // PubSub.subscribe(PubsubType.PUBSUB_DIGLOG_COMPONENT_AND_CONTAINER_CLOSE, (event, data) => {
    //   this.close()
    // })
  },
  data () {
    return {
      dialogShow: false,
      iframeLoading: true,
      iframeStyle: {},
      iframeSrc: '',
      formLabelWidth: '80px',
      name: '文章列表',
      bjComponent: null,
      data: null,
      activeName: '1',
      // 配置
      conf: require('./articles/config.js').conf,
      // ...
      quoteSystem: {},
      quoteSystemInput: ''

    }
  },
  watch: {
  },
  methods: {
    // 获取当前样式的配置
    getCurrentConf () {
      return this.conf[this.data.theme]
    },
    getComponentName () {
      var compname = this.iframeStyle.compname
      var temp = this.titleCase(compname.replace('_', ' ')).replace(' ', '')
      return temp.replace(temp[0], temp[0].toLowerCase())
    },
    titleCase (str) {
      return str.toLowerCase().replace(/( |^)[a-z]/g, (L) => L.toUpperCase())
    },
    // 列表数据处理
    getQuoteData (dataList) {
      let quoteData = []
      dataList.forEach(el => {
        let quote = {
          cateLink: {
            href: 'javascript:void(0)',
            target: '_self'
          },
          cateTitle: '',
          dataInfo: '',
          dataTitle: '',
          datetime: '',
          image: {
            alt: '',
            src: '',
            title: ''
          },
          link: {
            href: 'javascript:void(0)',
            target: '_self'
          }
        }
        quote.cateLink.target = this.data.config.ctarget
        quote.cateTitle = el.categoryQuote && el.categoryQuote.scategories && el.categoryQuote.scategories.name ? el.categoryQuote.scategories.name : ''
        quote.dataInfo = el.sarticle.synopsis
        quote.dataTitle = el.sarticle.title
        quote.datetime = el.sarticle.releasedAt
        quote.image.alt = el.repertoryQuote && el.repertoryQuote.srepertoryQuote && el.repertoryQuote.srepertoryQuote.config ? JSON.parse(el.repertoryQuote.srepertoryQuote.config).alt : ''
        quote.image.title = el.repertoryQuote && el.repertoryQuote.srepertoryQuote && el.repertoryQuote.srepertoryQuote.config ? JSON.parse(el.repertoryQuote.srepertoryQuote.config).title : ''
        quote.image.src = el.repertoryQuote && el.repertoryQuote.hrepertory ? functions.getRepertoryImageSrcByHostRepertory(el.repertoryQuote.hrepertory) : ''
        quote.link.target = this.data.config.atarget
        quoteData.push(quote)
      })
      return quoteData
    },
    // .............
    close () {
      this.dialogShow = false
      this.iframeSrc = ''
      this.iframeLoading = true
      this.iframeStyle = {}
      this.bjComponent = null
      this.data = null
      this.activeName = '1'
      // ...
      this.quoteSystem = {}
      this.quoteSystemInput = ''
    },
    saveclose () {
      this.quoteSystem = this.$refs['chooseArticlesSystemData'].getQuoteSystem()
      let quoteSystemData = this.$refs['chooseArticlesSystemData'].getSystemItemList()
      this.data.quote = this.getQuoteData(quoteSystemData)
      this.data.config.topCount = this.quoteSystem.topCount
      if (this.data.theme === '6' || this.data.theme === '7') {
        if (this.data.quote.length < 4) {
          this.$message.error('当列表样式选择为编号6或者编号7时，文章数量不能少于4！')
          return
        }
      }
      this.bjComponent._other.quoteSystem = this.quoteSystem
      this.bjComponent.render.data = _.cloneDeep(this.data)
      BackendjsFunctions.saveComponent(this.bjComponent)
      this.close()
    }
  },
  components: {
    SetDesignDialog,
    TextAlign,
    ChooseArticlesSystemData,
    TablesSystemType1,
    TablesSystemType2,
    TablesSystemType3,
    TablesSystemType4,
    FontWeight
  }
}

</script>

<style scoped>
.edit-container-u {
  width: 840px;
  min-height: 400px;
}
</style>
